<?php  
namespace app\common\services;

use \app\common\services\BaseService;
use \app\common\services\book\BookService;
use \app\models\book\Book;
use \app\models\pay\PayOrder;
use \app\models\pay\PayOrderItem;
use \Exception;
class PayOrderService extends BaseService{
	/**
	 * @param  [type] $items     [
	  [target_id 目标id,target_type 购买类型,price价格,quantity数量]
	 ]
	 */
	public static function createPayOrder($member_id,$items=[],$params=[]){
		$norstr=self::norstr();
		$total_price=0;//总价格
		$continue_cnt=0;//小于0的个数
		// var_dump($items);die;
		foreach($items as $v){
			//判断价格是否小于0
			if($v['price']<0){
				$continue_cnt++;
				continue;
			}
			
			$total_price+=$v['price'];
		}
		if($continue_cnt>=count($items)){
			return self::_err("商品items为空");
		}
		$discount=isset($params['discount'])?$params['discount']:0;
		$pay_price=$total_price-$discount;

		$total_price=sprintf("%0.2f",$total_price);//总支付金额
		$pay_price=sprintf("%0.2f",$pay_price);//实际支付金额
		$discount=sprintf("%0.2f",$discount);//优惠金额

		$connection=PayOrder::getDb();//开启事物
		$transaction=$connection->beginTransaction();
		try{
			
			
			//高并发悲观锁
			$tmp_book_table_name=Book::tableName();
			$tmp_target_id=array_column($items,'target_id');//target_id数组

			$sql="select id,stock from {$tmp_book_table_name} where id in (".implode(',',$tmp_target_id).") for update";
			// echo $sql;die;
			$tmp_book_list=$connection->createCommand($sql)->queryAll();//执行sql语句
			// var_dump($tmp_book_list);die;
			$tmp_book_unit_mapping=[];
			foreach($tmp_book_list as $v){
				//以target_id为键值stock为值
				$tmp_book_unit_mapping[$v['id']]=$v['stock'];
			}
			$model_pay_order = new PayOrder();
			$model_pay_order->order_sn = self::norstr();
			$model_pay_order->member_id = $member_id;
			$model_pay_order->pay_type = isset($params['pay_type'])?$params['pay_type']:0;
			$model_pay_order->pay_source = isset($params['pay_source'])?$params['pay_source']:0;
			$model_pay_order->target_type = isset($params['target_type'])?$params['target_type']:0;
			$model_pay_order->total_price = $total_price;
			$model_pay_order->discount = $discount;
			$model_pay_order->pay_price = $pay_price;
			$model_pay_order->note = isset($params['note'])?$params['note']:'';
			$model_pay_order->status = isset($params['status'])?$params['status']:-8;
			$model_pay_order->express_status = isset($params['express_status'])?$params['express_status']:-8;
			$model_pay_order->express_address_id = isset($params['express_address_id'])?$params['express_address_id']:0;
			$model_pay_order->pay_time = 0;
			$model_pay_order->updated_time = time();
			$model_pay_order->created_time =time();
			if(!$model_pay_order->save(0)){
				throw new Exception("创建订单失败");
			}
			foreach ($items as $_items) {
				$tmp_stock=$tmp_book_unit_mapping[$_items['target_id']];
				$res=Book::find()->where(['id'=>$_items['target_id']])->select('name')->one();
				
				if($tmp_stock<$_items['quantity']){
					throw new Exception($res->name."的库存不足,当前库存为".$tmp_stock."您提交的数目为".$_items['quantity']);
				}
				// var_dump($tmp_stock-$_items['quantity']);
				// echo $_items['target_id'];
				// die;
				
				$info=Book::find()->where(['id'=>$_items['target_id']])->one();
				$info->stock=$tmp_stock-$_items['quantity'];
				$res=$info->save(0);
				if(!$res){
					throw new Exception("下单失败请重新下单");
				}
				//添加数据->pay_order_item
				$new_pay_order_item=new PayOrderItem();
				$new_pay_order_item->pay_order_id=$model_pay_order->id;
				$new_pay_order_item->member_id=$member_id;
				$new_pay_order_item->quantity=$_items['quantity'];
				$new_pay_order_item->price=$_items['price'];
				$new_pay_order_item->target_type=$_items['target_type'];
				$new_pay_order_item->target_id=$_items['target_id'];
				$new_pay_order_item->status=isset($_items['status'])?$_items['status']:1;
				$new_pay_order_item->note=isset($_items['note'])?$_items['note']:'';
				$new_pay_order_item->created_time=time();
				$new_pay_order_item->updated_time=time();
				if(!$new_pay_order_item->save(0)){
					throw new Exception("创建订单失败");
				}
				BookService::setStockChangeLog($_items['target_id'],-$_items['quantity'],"在线购买");
				

			}
			$transaction->commit();
			return [
				'id'=>$model_pay_order->id,
				'order_sn'=>$model_pay_order->order_sn,
				'pay_price'=>$model_pay_order->pay_price,
			];
		}catch(Exception $e){
			$transaction->rollBack();//回滚
			
			return self::_err($e->getMessage());
		}

	}
	private static function norstr($length=16){
		//获取随机字符串
		$chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		$str='';
		for ($i=0; $i < $length; $i++) { 
			$str.=substr( $chars,mt_rand(0,strlen($chars)-1),1 );
		}
		return $str;
	}
	//取消库存 
    public static function backStock($pay_order_id,$status=0){
    	//归还库存
    	$update_stock=PayOrder::find()->join('inner join','pay_order_item','pay_order_item.pay_order_id=pay_order.id')->join('inner join','book','pay_order_item.target_id=book.id')->select('book.id as book_id,pay_order.id as pay_order_id,pay_order_item.quantity,book.stock')->where(['pay_order.id'=>$pay_order_id])->asArray()->one();
    	// var_dump($update_stock);die;
               
            $info=Book::find()->where(['id'=>$update_stock['book_id']])->one();
            $info->stock=$update_stock['stock']+$update_stock['quantity'];
            $info->updated_time=time();
            $res=$info->save(0);
            if(!$res){
                return self::_err("非法操作1");
            }
            $update_pay_order=PayOrder::find()->where(['id'=>$update_stock['pay_order_id']])->one();
            if(!$update_pay_order){
                return self::_err("非法操作2");
            }
            $update_pay_order->status=$status;
            $update_pay_order->save(0);
            return '取消成功';
        // return $this->renderJson(['url'=>'/user/order'],"取消成功~");
    }
}
?>